package com.example.dw.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.dw.dto.ActivityCommentDTO;
import com.example.dw.dto.ActivityQueryDTO;
import com.example.dw.dto.FavoriteDTO;
import com.example.dw.entity.*;
import com.example.dw.mapper.*;
import com.example.dw.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动服务实现类
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityCommentMapper activityCommentMapper;

    @Autowired
    private UserFavoriteActivityMapper userFavoriteActivityMapper;

    @Autowired
    private ActivityBigTypeMapper activityBigTypeMapper;

    @Autowired
    private QRMapper qrMapper;

    @Autowired
    private ActivitySessionMapper activitySessionMapper;

    @Autowired
    private SessionPriceMapper sessionPriceMapper;

    @Override
    public Activity getActiveById(Integer activityid) {
        if (activityid == null) {
            throw new RuntimeException("活动ID不能为空");
        }
        Activity activity = activityMapper.getActivityById(activityid);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
        //  根据互动id获取所有场次，再遍历所有场次id获取价格
        List<ActivitySession> activitySessions = activitySessionMapper.getActivitySessionByActivityId(activityid);
        log.info("活动ID: {}, 查询到的场次数量: {}", activityid, activitySessions != null ? activitySessions.size() : 0);
        
        // 如果activitySessions为null，初始化为空列表
        if (activitySessions == null) {
            activitySessions = new java.util.ArrayList<>();
        } else {
            for (ActivitySession activitySession : activitySessions) {
                List<SessionPrice> sessionPrices = sessionPriceMapper.getSessionPriceBySessionId(activitySession.getSessionid());
                log.info("场次ID: {}, 查询到的价格数量: {}", activitySession.getSessionid(), sessionPrices != null ? sessionPrices.size() : 0);
                // 判断sessionPrices是否为空，不为空则设置
                activitySession.setActivityPrices(sessionPrices);
            }
            
            // 在移除之前记录当前数量
            int beforeRemove = activitySessions.size();
            // 遍历activitySessions，activitySession.activityPrices为空则移除
            activitySessions.removeIf(activitySession -> {
                boolean shouldRemove = activitySession.getActivityPrices() == null || activitySession.getActivityPrices().isEmpty();
                if (shouldRemove) {
                    log.warn("移除场次ID: {}, 原因: 价格列表为空", activitySession.getSessionid());
                }
                return shouldRemove;
            });
            int afterRemove = activitySessions.size();
            log.info("移除前场次数量: {}, 移除后场次数量: {}", beforeRemove, afterRemove);
        }
        
        activity.setActivitySessions(activitySessions);
        return activity;
    }

    @Override
    public Map<String, Object> getActiveCommentByPage(ActivityCommentDTO commentDTO) {
        Integer page = commentDTO.getPage() != null && commentDTO.getPage() > 0 ? commentDTO.getPage() : 1;
        Integer size = commentDTO.getSize() != null && commentDTO.getSize() > 0 ? commentDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<ActivityComment> comments = activityCommentMapper.getCommentsByActivityId(
                commentDTO.getActivityid(), offset, size);
        Integer total = activityCommentMapper.getCommentCountByActivityId(commentDTO.getActivityid());

        Map<String, Object> result = new HashMap<>();
        result.put("list", comments);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public List<ActivityComment> getActiveComment(Integer activityid) {
        if (activityid == null) {
            throw new RuntimeException("活动ID不能为空");
        }
        return activityCommentMapper.getAllCommentsByActivityId(activityid);
    }

    @Override
    public void addActiveComment(Integer userid, ActivityCommentDTO commentDTO) {
        // 检查活动是否存在
        Activity activity = getActiveById(commentDTO.getActivityid());

        // 创建评论
        ActivityComment comment = new ActivityComment();
        comment.setUserid(userid);
        comment.setActivityid(commentDTO.getActivityid());
        comment.setStars(commentDTO.getStars());
        comment.setContent(commentDTO.getContent());
        comment.setCreatedAt(LocalDateTime.now());

        activityCommentMapper.insert(comment);

        // 更新活动评论数量
        Integer commentCount = activityCommentMapper.getCommentCountByActivityId(commentDTO.getActivityid());
        Activity updateActivity = new Activity();
        updateActivity.setActivityid(commentDTO.getActivityid());
        updateActivity.setActivityCommentCount(commentCount);
        activityMapper.updateById(updateActivity);
    }

    @Override
    public void changeFavorite(Integer userid, FavoriteDTO favoriteDTO) {
        // 检查当前收藏状态
        UserFavoriteActivity existingFavorite = userFavoriteActivityMapper.checkFavorite(
                userid, favoriteDTO.getActivityid());

        if (existingFavorite != null) {
            // 更新现有记录的状态
            Integer newState = (existingFavorite.getState() == 0) ? 1 : 0; // 切换状态
            userFavoriteActivityMapper.updateFavoriteState(
                    userid, favoriteDTO.getActivityid(), newState);
        } else {
            // 创建新的收藏记录，默认为收藏状态
            userFavoriteActivityMapper.insertFavorite(userid, favoriteDTO.getActivityid(), 0);
        }
    }

    @Override
    public Boolean isFavorite(Integer userid, Integer activityid) {
        UserFavoriteActivity favorite = userFavoriteActivityMapper.checkFavorite(userid, activityid);
        return favorite != null && favorite.getState() == 0;
    }

    @Override
    public Map<String, Object> getActiveByPageIng(ActivityQueryDTO queryDTO) {
        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<Activity> activities = activityMapper.getActiveByPageIng(offset, size);
        Integer total = activityMapper.getActiveCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", activities);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public Map<String, Object> getActiveByPageEd(ActivityQueryDTO queryDTO) {
        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<Activity> activities = activityMapper.getActiveByPageEd(offset, size);
        Integer total = activityMapper.getExpiredActiveCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", activities);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public Map<String, Object> getAllBigTypeByPage(ActivityQueryDTO queryDTO) {
        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<ActivityBigType> bigTypes = activityBigTypeMapper.getAllBigTypeByPage(offset, size);
        Integer total = activityBigTypeMapper.getBigTypeCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", bigTypes);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public Map<String, Object> getActiveByMonth(ActivityQueryDTO queryDTO) {
        if (StrUtil.isBlank(queryDTO.getMonth())) {
            throw new RuntimeException("月份参数不能为空");
        }

        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<Activity> activities = activityMapper.getActiveByMonth(queryDTO.getMonth(), offset, size);
        Integer total = activityMapper.getActiveCountByMonth(queryDTO.getMonth());

        Map<String, Object> result = new HashMap<>();
        result.put("list", activities);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public List<QR> getQR() {
        return qrMapper.getAllQR();
    }

    @Override
    public List<Activity> getActiveByMonthAll(String month) {
        if (StrUtil.isBlank(month)) {
            throw new RuntimeException("月份参数不能为空");
        }
        return activityMapper.getActiveByMonthAll(month);
    }

    @Override
    public Map<String, Object> getActivedByPage(ActivityQueryDTO queryDTO) {
        if (queryDTO.getBigid() == null) {
            throw new RuntimeException("活动大类ID不能为空");
        }

        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<Activity> activities = activityMapper.getActivedByPage(queryDTO.getBigid(), offset, size);
        Integer total = activityMapper.getActivedCountByBigId(queryDTO.getBigid());

        Map<String, Object> result = new HashMap<>();
        result.put("list", activities);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }
} 